package com.lxk.interceptor;

import com.lxk.aspect.Trace;
import com.lxk.dao.BlogDbDao;
import com.lxk.domain.BlogDbEntity;
import com.lxk.utils.TraceUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.util.ObjectUtils;
import org.springframework.web.servlet.View;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.*;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * Created by Lxk on 2020/6/25.
 */
public class ViewCountInterceptor extends HandlerInterceptorAdapter {

    private static Logger logger = LoggerFactory.getLogger(ViewCountInterceptor.class);

    private BlogDbDao blogDbDao;

    private Map<String,AtomicInteger> idCountMap = new ConcurrentHashMap<>();

    ScheduledExecutorService executor = Executors.newSingleThreadScheduledExecutor();

    public ViewCountInterceptor(BlogDbDao blogDbDao) {
        this.blogDbDao = blogDbDao;
        this.executor.scheduleAtFixedRate(new Runnable() {
            @Override
            public void run() {
                TraceUtil.genTrace("read_count_task");
                logger.info("更新访问量开始......");
                for(Map.Entry<String,AtomicInteger> entry : idCountMap.entrySet()){
                    try{
                        String id = entry.getKey();
                        BlogDbEntity blogDbEntity = blogDbDao.queryById(Long.parseLong(id));
                        if(ObjectUtils.isEmpty(blogDbEntity)){
                            continue;
                        }
                        blogDbEntity.setViewCount(entry.getValue().get()+blogDbEntity.getViewCount());
                        //计数更新成功则成功并归0，否则不归0，等待下次更新
                        if(blogDbDao.updateByVersion(blogDbEntity)>0){
                            //计数更新成功
                            entry.getValue().set(0);
                        }
                    }catch (Exception e){
                        logger.info("统计文章id:{}的访问量异常，count:{},e:",entry.getKey(),entry.getValue(),e);
                    }
                }
                TraceUtil.cleanTrace();
            }
        },5,10,TimeUnit.SECONDS);
    }

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        String id = request.getParameter("id");
        if(idCountMap.keySet().contains(id)){
            idCountMap.get(id).getAndIncrement();
        }else{
            idCountMap.put(id,new AtomicInteger(1));
        }
        return super.preHandle(request, response, handler);
    }



}
